﻿using Serilog;
using System;
using System.Runtime.InteropServices;

namespace WatchDog;

public class SetSystemDateTime
{
    [DllImport("Kernel32.dll")]
    public static extern bool SetLocalTime(ref SystemTime sysTime);

    public static bool SetLocalTimeByStr(string timestr)
    {
        bool flag = false;
        SystemTime sysTime = new SystemTime();
        DateTime dt = Convert.ToDateTime(timestr);
        sysTime.wYear = Convert.ToUInt16(dt.Year);
        sysTime.wMonth = Convert.ToUInt16(dt.Month);
        sysTime.wDay = Convert.ToUInt16(dt.Day);
        sysTime.wHour = Convert.ToUInt16(dt.Hour);
        sysTime.wMinute = Convert.ToUInt16(dt.Minute);
        sysTime.wSecond = Convert.ToUInt16(dt.Second);
        try
        {
            flag = SetSystemDateTime.SetLocalTime(ref sysTime);
        }
        catch (Exception ex)
        {
            Log.Logger.Error(ex,"设置系统时间出错");
        }
        return flag;
    }
}

/**
 * 系统时间的设置
 **/
[StructLayout(LayoutKind.Sequential)]
public struct SystemTime
{
    public ushort wYear;
    public ushort wMonth;
    public ushort wDayOfWeek;
    public ushort wDay;
    public ushort wHour;
    public ushort wMinute;
    public ushort wSecond;
    public ushort wMiliseconds;
}
